在 CDK 裡也提供了 Drag & Drop 的功能,我們透過這個來實作看版的頁面。

首先,我們會使用 cdkDropListGroup 指令定義哪一個區域可以拖曳,而這個區域有未處理、處理中與已完成三種不同的工作事項狀態。
<div class="board" cdkDropListGroup>
  <section>
    
  </section>
  <section>
  <h3>處理中</h3>
  </section>
  <section>
    <h3>已完成</h3>
  </section>
</div>
接著就在三種不同的工作事項狀態中利用 cdkDropList 與 cdkDropListData 來設定此區塊拖曳資料記錄的位置,並且在可以拖曳的對象使用 cdkDrag指令元件。
<h3>未處理</h3>
<div
  cdkDropList
  [cdkDropListData]="waiting()"
  (cdkDropListDropped)="onDrop($event)"
>
  @for (task of waiting(); track $index) {
    <app-task-card [task]="task" cdkDrag></app-task-card>
  }
</div>
最後,就是來實作 cdkDropListDropped 這個拖曳事件的內容,其中會使用到 CDK 所提供的 moveItemInArray 與 transferArrayItem 兩個方法,分別來處理在同一個區域時要變更順序,以及移至不同區域時更新資料記錄。
onDrop(event: CdkDragDrop<TaskItem[]>) {
  if (event.previousContainer === event.container) {
    moveItemInArray(
      event.container.data,
      event.previousIndex,
      event.currentIndex
    );
  } else {
    transferArrayItem(
      event.previousContainer.data,
      event.container.data,
      event.previousIndex,
      event.currentIndex
    );
  }
}
如此一來,就可以實作出一個簡易的看板功能。